<template>
  <div>
    <div
      class="-mt-46 h-[calc(100vh-15px)] custom-navbar-wrapper pt-46 flex flex-col"
    >
      <div class="pt-15 px-15 flex items-center justify-between">
        <NormalTabs
          class="flex-1"
          :tabs="CATEGORIES.map(item => ({ id: item.id, name: item.name }))"
          :active-id="activeCategoryId"
          :tab-class="tabClass"
          @update:active-id="activeCategoryId = $event"
        />
        <div
          class="text-999999 text-14 flex items-center"
          @click="navigateTo('MyHumanHistory')"
        >
          <div>历史记录</div>
          <!-- 使用阿里云图标库图标（注意前缀） -->
          <svg-icon name="icon-gengduo" :size="10" color="#999" />
        </div>
      </div>
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar flex-1"
        :style="popoverVisible ? 'overflow-y: hidden;' : ''"
      >
        <div ref="scrollContent" class="scroll-view__content">
          <!-- 将EntryCards放在这里，确保跟随页面滚动 -->
          <div class="overflow-hidden">
            <EntryCards :active-category-id="activeCategoryId" />
          </div>

          <!-- 数字人列表 -->
          <div v-if="activeCategoryId === 'myHuman'" class="mx-15 mt-20">
            <div class="text-16 font-bold">我的数字人</div>
            <HumanListItem
              v-for="item in myHumanList"
              :key="item.humanId"
              :item="item"
            />
          </div>

          <!-- 音色列表 -->
          <div v-if="activeCategoryId === 'timbre'" class="mx-15 mt-20">
            <div class="text-16 font-bold">我的音色</div>
            <TimbreListItem
              v-for="item in timbreList"
              :key="item.timbreId"
              :item="item"
              :is-asset-list="true"
              @update:popover-visible="popoverVisible = $event"
            />
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="py-20 flex justify-center items-center">
            <van-loading size="24px" vertical>
              <span class="text-13 text-999 mt-10">加载中...</span>
            </van-loading>
          </div>

          <!-- 没有更多数据 -->
          <div
            v-if="currentList.length > 0 && !isLoading"
            class="py-15 text-center text-13 text-999"
          >
            <span class="inline-block px-10 py-5 rounded-full bg-gray-100"
              >没有更多数据了</span
            >
          </div>
          <!-- 空状态 -->
          <EmptyState
            v-if="!isLoading && currentList.length === 0"
            class="mt-50"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import NormalTabs from "@/components/NormalTabs/index.vue";
import { IMG_CDN_39 } from "@/constants";
import { showToast } from "vant";
import {
  getMyHumanInfoList,
  getNoFailTimbreInfoList,
  type MyHumanInfoData,
  type NoFailTimbreInfoData
} from "@/api/MyHuman";
import EntryCards from "@/views/MyHuman/EntryCards.vue";
import router from "@/router";
import HumanListItem from "./HumanListItem.vue";
import TimbreListItem from "./TimbreListItem.vue";
import { useRoute } from "vue-router";

defineOptions({
  name: "MyHuman"
});

const route = useRoute();

// 分类配置
const CATEGORIES = [
  { id: "myHuman", name: "数字人", api: getMyHumanInfoList },
  { id: "timbre", name: "音色", api: getNoFailTimbreInfoList }
];
const activeCategoryId = ref<string>("myHuman");

// 样式配置
const tabClass = ref({
  textColor: "text-333333"
});

// 使用类型化的数据结构
interface HistoryData {
  myHuman: MyHumanInfoData[];
  timbre: NoFailTimbreInfoData;
}

const historyData = ref<HistoryData>({
  myHuman: [],
  timbre: { infoList: [] }
});

// 计算属性获取当前列表
const currentList = computed(() => {
  if (activeCategoryId.value === "timbre") {
    return historyData.value.timbre.infoList || [];
  } else {
    return historyData.value[activeCategoryId.value] || [];
  }
});

// 计算属性分离不同类型的数据
const myHumanList = computed(() => historyData.value.myHuman);
const timbreList = computed(() => historyData.value.timbre.infoList || []);

// 弹窗显示状态
const popoverVisible = ref(false);

// 加载状态
const isLoading = ref(false);

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
const scrollContent = ref<HTMLElement | null>(null);

// 统一加载函数
const loadHistoryData = async () => {
  if (isLoading.value) return;

  try {
    isLoading.value = true;
    const category = activeCategoryId.value;
    const apiFunc = CATEGORIES.find(c => c.id === category)?.api;
    if (!apiFunc) return;

    historyData.value[category] = await apiFunc();
  } catch (error) {
    console.error("加载失败:", error);
    showToast("加载失败，请稍后再试");
  } finally {
    isLoading.value = false;
  }
};

// 监听分类切换
watch(activeCategoryId, newId => {
  if (
    (newId === "timbre" && historyData.value.timbre.infoList?.length === 0) ||
    (newId === "myHuman" && historyData.value.myHuman.length === 0)
  ) {
    loadHistoryData();
  }
});

// 导航到指定页面
const navigateTo = (routeName: string) => {
  router.push({ name: routeName });
};

onMounted(() => {
  // 初始化加载时也根据路由参数判断是否需要重新加载数据
  const routeType = route.params.type ? String(route.params.type) : null;
  if (routeType && CATEGORIES.some(c => c.id === routeType)) {
    activeCategoryId.value = routeType;
  }
  loadHistoryData();
});
</script>

<style scoped lang="less"></style>
